<?php

class Admin_UserController extends ExtLb_Controller_Action
{

    private $userTbl;
    private $userForm ;
    private $studentTbl;
    
    private $storage;
    private $auth;

    public function init()
    {
    	$this->loadLayout('admin', 'layout');
    	$this->loadCss('admin', 'user');
    	
    	$this->userTbl  	= new Admin_Model_User();
    	$this->studentTbl	= new Admin_Model_Student();
    	$this->userForm 	= new Admin_Form_UserForm();
    	
    	$this->auth 		= Zend_Auth::getInstance();
    	$this->storage		= $this->auth->getStorage()->read(); 
    	
    	
    }

    public function indexAction()
    {
    	
    	$userSelect = $this->userTbl->listUser("quyen ='sinhvien'");
    	
    	//xu ly tim kiem
    	if(isset($_GET['search_box_sumit']) && isset($_GET['student'])){
    		if(empty($_GET['search_box_text'])){
    			$this->jDialogMessage('Thông báo','Hãy nhập vào tên sinh viên hoặc mã sinh viên (username) trước!!!');
    		}else{
    			$userSelect = $this->userTbl->listUser(
    					"quyen ='sinhvien' and (
    					u.ten like '%".$_GET['search_box_text']."%' or
    					u.username like '%".$_GET['search_box_text']."%')"
    			);
    		}
    	}
    	
    	//
    	//xu ly loc
    	if(isset($_GET['tbn_filter']) && $_GET['tbn_cate'] != "0" && isset($_GET['student'])){
    		$userSelect = $this->userTbl->listUser("quyen ='sinhvien' and lop.tenLop = '".$_GET['tbn_cate']."'");
    	}
    	//
    	//xu ly phan trang
    	$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($userSelect));
    	if($paginator->getTotalItemCount() == 0){
    		$this->jDialogMessage('Thông báo','Không tìm thấy (!_!) :( ');
    	}
    	
    	$paginator->setItemCountPerPage(30)
    			->setCurrentPageNumber($this->_getParam('page',1));
    	
    			
    			
    	$this->view->paginator = $paginator;
    	$this->view->tenLop = $this->userTbl->getAllLop();
    	
    	//
    	// === Forware when del
    	if(isset($_GET['del'])){
    		$this->_forward('delete','user','admin');
    	}
    }

    public function addAction()
    {
    	//	== Filter
    	$this->forward_When_Filter();
    	//	=== Search
    	$this->forward_when_search();
    	
    	if(isset($_GET['edit']) && !empty($_GET['user'])){//sua
    		$this->userForm->addAction('edit');
	    	$this->userForm->addSubmitButton('cmdEdit', 'Cập nhập');
	    		
    		$user = $this->userTbl->fetchUser($_GET['user']); //get info username
    		
    		$this->userForm->getElement('txtUser')->setAttrib('readonly', 'ok')->setValue($user['username']);
    		$this->userForm->getElement('txtPass')->setValue($user['password']);
    		$this->userForm->getElement('txtHoDem')->setValue($user['hoDem']);
    		$this->userForm->getElement('txtTen')->setValue($user['ten']);
    		$this->userForm->getElement('cbbRole')->setValue($user['quyen']);
    		$this->userForm->getElement('txtNgaySinh')->setValue($user['ngaySinh']);
    		$this->userForm->getElement('txtEmail')->setValue($user['email']);
    	}else{//them moi
    		$this->userForm->addSubmitButton('cmdAdd', 'Thêm');
	    	$this->userForm->addAction('add');
	    	
    		if($this->userForm->isValid($this->_request->getPost())){
	    		if(isset($_POST['cmdAdd'])){
	    			try {
	    				$user 		= $this->_getParam('txtUser');
		    			$pass 		= $this->_getParam('txtPass');
		    			$hoDem 		= $this->_getParam('txtHoDem');
		    			$ten 		= $this->_getParam('txtTen');
		    			$email		= $this->_getParam('txtEmail');
		    			$ngaySinh 	= $this->_getParam('txtNgaySinh');
		    			$quyen 		= $this->_getParam('cbbRole');
		    			
		    			$this->userTbl->addUser($user, $pass, $quyen, $hoDem, $ten,$email, $ngaySinh);
		    			
		    			$this->_request->clearParams();
		    			$this->jDialogMessage('(n_n) Thông báo','Đã thêm!!!');
		    				
	    			} catch (Exception $e) {
	    				$this->jDialogMessage('Thông báo','(!_!)  Đã xảy ra lỗi. Có thể tên đăng nhập này đã tồn tại. Hãy Thử lại với tên khác');
	    			}
	    			
	    			$this->_forward('index','user','admin');
	    		}
    		}
    	}
        
        $this->view->userForm = $this->userForm;
        
    }

    public function deleteAction(){
    	try {
    		//	=== Filter
    		$this->forward_When_Filter();
    		//	=== Search
    		$this->forward_when_search();
    	
    		$dataStudents = $this->studentTbl->fetchSql("select username from sinhvien");
	
    		//
	        // === Del multi
	    	if(isset($_GET['del']) && !empty($_GET['lop-check'])){
	    		$arrDel = $_GET['lop-check'];
	    		for ($i=0; $i<count($arrDel); $i++){
	    			$this->userTbl->deleteUser($arrDel[$i]);

	    			//
	    			// === Xoa thông tin sinh vien trong bang sinhvien
	    			if($this->in_array($arrDel[$i], $dataStudents,'username')){
		    			$this->studentTbl->deleteStudent($arrDel[$i]);
	    			}
	    		}
	    	}
	    	
	    	// == Del one
	    	if(isset($_GET['delete']) && !empty($_GET['user'])){
	    		$this->userTbl->deleteUser($_GET['user']);
	    		// Xoa thong tin trong bang sinhvien.
	    		if($this->in_array($arrDel[$i], $dataStudents,'username')){
		    			$this->studentTbl->deleteStudent($_GET['user']);
	    		}
	    	}
	    	
	    	$this->_redirect('/admin/user');
    	} catch (Exception $e) {
    		$this->jDialogMessage('Lỗi','(!_!) Đã xảy ra lỗi. Hãy thử lại');
    		$this->_forward('index','user','admin');
    	}
    	
    	
    }

    public function editAction(){
    	//	=== Filter
    	$this->forward_When_Filter();
    	//	=== Search
    	$this->forward_when_search();
    	
    	if($this->userForm->isValid($this->_request->getPost())){
    		if(isset($_POST['cmdEdit'])){
    			try {
    				$user 		= $this->_getParam('txtUser');
		    		$pass 		= $this->_getParam('txtPass');
		    		$hoDem 		= $this->_getParam('txtHoDem');
		    		$ten 		= $this->_getParam('txtTen');
		    		$email		= $this->_getParam('txtEmail');
		    		$ngaySinh 	= $this->_getParam('txtNgaySinh');
		    		$quyen 		= $this->_getParam('cbbRole');
		    		$lop		= $this->_getParam('cbbLop');
		    			
		    		$this->userTbl->updateUser($pass, $quyen, $hoDem, $ten,$email, $ngaySinh,$user);
		    		
		    		//if da co thi cap nhap, chua co thi them
		    		$dataStudents = $this->studentTbl->fetchSql("select username from sinhvien");
	
		    		if($this->in_array($user, $dataStudents,'username')){
		    			$this->studentTbl->updateStudent($user, $lop);
		    		}else{
	 					$this->studentTbl->addStudent($user, $lop);	
		    		}
		    		
		    		$this->jDialogMessage('Thông báo','Thành công!!!');
		    			
    			} catch (Exception $e) {
    				$this->jDialogMessage('Thông báo','(!_!)  Đã xảy ra lỗi. Hãy Thử lại. (-_-;)');
    			}
    		}
    	}
    	$this->_forward('index','user','admin');
    }

    public function importAction(){
        if(isset($_POST['cmdUImport'])){
			
        	try {
        		// === Filter
        		$this->forward_When_Filter();
        		//	=== Search
    			$this->forward_when_search();
        		
        		if ($_FILES['fUImport']['error'] >1 ){
        			$this->jDialogMessage('Cảnh báo','Bạn chưa chọn file để nhập vào');
        			$this->_forward('add','user','admin');
        			
        			$_REQUEST['fUImportchoose'] = true;
        			
        			return ;
        		}else{
        			$_REQUEST['fUImport'] = false;
        		}
				move_uploaded_file($_FILES["fUImport"]["tmp_name"],WEB_ROOT."/docs/". $_FILES["fUImport"]["name"]);
				
				$fileName = WEB_ROOT."/docs/".$_FILES['fUImport']['name'];
	        	//lay du lieu tu file excel
	        	$dataFromExcel = $this->importFromExcel($fileName);
	        	$rowsNum = $dataFromExcel->rowcount();//lay so dong
	        	$colsNum = $dataFromExcel->colcount();//lay so cot
	
	        	// 
	        	// === import thong tin user vao users table
	        	for($i=2; $i<$rowsNum; $i++){
	        		//
	        		// === If co 1 dong nao do trong thi bo qua
	        		if ($dataFromExcel->val($i, 1) == NULL 
	        			) continue;
		        	@$this->userTbl->addUser(
		        					trim($dataFromExcel->val($i, 1)),
		        					$dataFromExcel->val($i, 2), 
		        					$dataFromExcel->val($i, 3), 
		        					$dataFromExcel->val($i, 4), 
		        					$dataFromExcel->val($i, 5),
		        					$dataFromExcel->val($i, 6), 
		        					$dataFromExcel->val($i, 7)
	        		);
	        		
		        	// 
		        	// === Cap nhap lop cho user trong bang sinhvien
        			@$this->studentTbl->addStudent(
        								trim($dataFromExcel->val($i, 1)),
        								$dataFromExcel->val($i, 8)
        							);
		    			
		    		}

	        	//
	        	// === 
	        	$this->jDialogMessage('Thông báo','Nhập thành công!!!!!! ');
	        	
	        		
        	} catch (Exception $e) {
        		$this->jDialogMessage('Lỗi','(!_!) Đã xảy ra lỗi trong quá trình xử lý. Kiểm tra lại mẫu file import');
        	}
			        	
        	$this->_forward('index','user','admin');
		}else{
			$this->_redirect('/admin/user/index');
		}        	
	}

	function teacherAction() {
		$userSelect = $this->userTbl->listUser("quyen = 'giaovien'");
    	
    	//xu ly tim kiem
    	if(isset($_GET['search_box_sumit']) && isset($_GET['teach'])){
    		if(empty($_GET['search_box_text'])){
    			
    			$this->jDialogMessage('Thông báo','Hãy nhập vào tên sinh viên hoặc mã sinh viên (username) trước!!!');
    			$this->_forward('index','user','admin');
//    			$this->_redirect('/admin/user/');
    		}else{
    			$userSelect = $this->userTbl->listUser(
    					"u.ten like '%".$_GET['search_box_text']."%' or
    					u.username like '%".$_GET['search_box_text']."%' and 
    					u.quyen ='giaovien'"
    			);
    		}
    	}
    	
    	//
    	//xu ly loc
    	if(isset($_GET['tbn_filter']) && $_GET['tbn_cate'] != "0" && isset($_GET['teach'])){
    		$userSelect = $this->userTbl->listUser("lop.tenLop = '".$_GET['tbn_cate']."'");
    	}
    	//
    	//xu ly phan trang
    	$paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($userSelect));
    	$paginator->setItemCountPerPage(30)
    			->setCurrentPageNumber($this->_getParam('page',1));
    			
    	$this->view->paginator = $paginator;
    	$this->view->tenLop = "";//$this->userTbl->getAllLop();
    	
    	
	}
	
	public function yourprofileAction(){
		
		$this->view->yourprofile = $this->userTbl->fetchUser($this->storage->username)->toArray();
		
	}
	///////////////////////////////////////////////////////////////////
	//	=== PRIVATE FUNCTION										//
	//////////////////////////////////////////////////////////////////
	
	private function in_array($valueCheck,$arrayCheck,$stringKey){
		foreach ($arrayCheck as $key=>$value) {
			if( trim($value[$stringKey]) == trim($valueCheck)) return TRUE;
		}
		return FALSE;
	}
	
	private function forward_When_Filter(){
		if(isset($_GET['tbn_filter']) && $_GET['tbn_cate'] != "0" && isset($_GET['student'])){
			$this->_forward('index','user','admin');
		}
	}
	
	private function forward_when_search(){
		if(isset($_GET['search_box_sumit']) && isset($_GET['student'])){
			$this->_forward('index','user','admin');
		}
	}
}









